<template>
  <el-dialog :title="title" v-model="dialogVisible" width="600px">
    <!--     :rules="rules" -->
    <el-form
      :model="ruleForm"

      ref="ruleFormRef"
      label-width="120px"
    >
      <el-form-item label="关联菜单" prop="menuIdList" v-if="dialogVisible">
        <el-tree
        :data="menuOption"
        :props="propsDefault"
        show-checkbox
        default-expand-all
        :default-checked-keys="ruleForm.menuIdList"
        node-key="id"
        ref="treeRef"
        @check-change="handleChange" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submit"> 确 定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { defineComponent, watch, computed, ref } from "vue";
import { orgRelativeMenu, getOrgInfo, getMenuTree } from "@/api/system";
import useEditDialog from "@/hooks/useEditDialog";

export default defineComponent({
  name: "EditDialog",
  emits: ["update-list"],
  setup(props, { emit }) {
    const DEFAULT_FORM = {
      menuIdList: [], // 组织列表
    };
    const propsDefault = ref({ label: "name" });
    // const rules = computed(() => {
    //   const baseRules = {
    //     // 表单校验规则
    //     menuIdList: [{ required: true, message: "请选择相关菜单" }],
    //   };
    //   return baseRules;
    // });

    const {
      dialogVisible,
      title,
      ruleForm,
      ruleFormRef,
      open,
      close,
      submit,
      isEditDialog,
    } = useEditDialog({
      createApi: orgRelativeMenu,
      editApi: orgRelativeMenu,
      defaultForm: DEFAULT_FORM,
      emit,
    });

    const getDetail = async () => {
      const res = await getOrgInfo(ruleForm.value.id);
      const menuIdList = [];
      res.data.menuList.map((item) => {
        menuIdList.push(item.id);
      });

      ruleForm.value.id = res.data.id
      ruleForm.value.menuIdList = menuIdList

      ruleFormRef.value.clearValidate();
    };

    watch(dialogVisible, () => {
      if (dialogVisible.value) {
        if (isEditDialog.value) {
          getDetail();
        } else {
          // ruleForm.value.menus = null
        }
      }
    });
    const menuOption = ref([]);
    const getMenu = async () => {
      const res = await getMenuTree();
      menuOption.value = res.data;
    };
    getMenu();
    const handleChange = (val) => {
      ruleForm.value.menuIdList = treeRef.value.getCheckedKeys()
    };
    const treeRef = ref(null)
    return {
      treeRef,
      propsDefault,
      handleChange,
      menuOption,
      isEditDialog,
      ruleFormRef,
      ruleForm,
      // rules,
      dialogVisible,
      title,
      open,
      close,
      submit,
    };
  },
});
</script>
